#!/usr/bin/env bash

# Changes the GTK icon theme of the system
# To run: ./changeicon.sh SomeIconThemeName
# To see a list of installed icon themes: ./changeicon.sh

# Icon theme not given
if [ -z "${1}" ]; then
	echo 'Please pass an icon theme name:'
	echo "  ${0} SomeIconThemeName"
	echo 'You can use these as the icon theme name:'

	find '/usr/share/icons/' '/usr/local/share/icons/' "$HOME/.icons/" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | while IFS= read -r line; do
		# To not include themes that are not actually complete icon themes
		if [ -d "${line}" ] && [ -f "${line}/index.theme" ]; then
			echo "  - $(basename "$line")"
		fi
	done
	exit 1
fi

# GTK3
if [ ! -d "/usr/share/icons/${1}" ] && [ ! -d "/usr/local/share/icons/${1}" ] && [ ! -d "$HOME/.icons/${1}" ]; then echo "The icon theme does not exist"; exit 2; fi
ICON_THEME="${1}"
if [ -f "$HOME/.config/gtk-3.0/settings.ini" ]; then
	if [ -n "$(grep 'gtk-icon-theme-name' $HOME/.config/gtk-3.0/settings.ini)" ]; then
		sed -i'' -e "s/gtk-icon-theme-name=\(.*\)/gtk-icon-theme-name=${ICON_THEME}/1" "${HOME}/.config/gtk-3.0/settings.ini"
	else
		echo "gtk-icon-theme-name=${ICON_THEME}" >> "$HOME/.config/gtk-3.0/settings.ini"
	fi
else
	mkdir -p "$HOME/.config/gtk-3.0/"
	echo "[Settings]"$'\n'"gtk-icon-theme-name=${ICON_THEME}" > "$HOME/.config/gtk-3.0/settings.ini"
fi

# GTK2
if [ -f "$HOME/.gtkrc-2.0" ]; then
	if [ -n "$(grep 'gtk-icon-theme-name' $HOME/.gtkrc-2.0)" ]; then
		sed -i'' -e "s/gtk-icon-theme-name=\(.*\)/gtk-icon-theme-name=\"${ICON_THEME}\"/1" "$HOME/.gtkrc-2.0"
	else
		echo "gtk-icon-theme-name=\"${ICON_THEME}\"" >> "$HOME/.gtkrc-2.0"
	fi
else
	echo "gtk-icon-theme-name=\"${ICON_THEME}\"" > "$HOME/.gtkrc-2.0"
fi

# Call Gsettings
if [ -n "$(command -v gsettings)" ]; then
	gsettings list-schemas | grep 'org.gnome.desktop.interface' &>/dev/null
	if [ "$?" -gt "0" ]; then
		echo 'There are no org.gnome.desktop.interface schema found. Try installing gsettings-desktop-schemas and then continue...'
	elif [ "$(gsettings writable org.gnome.desktop.interface icon-theme)" = 'true' ]; then
		gsettings set org.gnome.desktop.interface icon-theme "${ICON_THEME}"
	else
		echo 'The icon-theme key is not writable. The process may not be successful.'
	fi
else
	echo 'Error: gsettings binary not found on the system. Changes might not be fully applied.'
fi

# Success message
echo "GTK icon theme changed to $ICON_THEME. You may have to restart apps for the changes to take effect."
